package com.cdvtc.flower.dao.impl;

import com.cdvtc.flower.dao.MerchantsDao;
import com.cdvtc.flower.model.Category;
import com.cdvtc.flower.model.Merchants;
import com.cdvtc.flower.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MerchantsDaoImpl implements MerchantsDao {
    private Connection conn;
    @Override
    public List<Merchants> getALLMerchants() {
        List<Merchants> merchants = new ArrayList<>();

        // 获取连接
        conn = DBUtil.getConnection();
//        Statement st = null;


        // 创建Staement
        try(Statement st = conn.createStatement()) {
            // 执行SQL，获取ResultSet
            String sql = "select * from merchants";
            try(ResultSet rs = st.executeQuery(sql)) {
                // 从rs中获取数据
                while (rs.next()) {
                    int merchant_id = rs.getInt("merchant_id");
                    String store_name = rs.getString("store_name");
                    String address = rs.getString("address");
                    String phone = rs.getString("phone");
                    String email = rs.getString("email");
                    String password = rs.getString("password");

                    // 将数据写入封装对象
                    Merchants merchant = new Merchants();

                    merchant.setMerchant_id(merchant_id);
                    merchant.setEmail(email);
                    merchant.setPassword(password);
                    merchant.setPhone(phone);
                    merchant.setStore_name(store_name);
                    merchant.setAddress(address);

                    //将对象往往集合类中
                    merchants.add(merchant);
                }
            }

            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return merchants;
    }
    @Override
    public void updateMerchants(Merchants merchants) {
        try (Connection conn = DBUtil.getConnection(); // 使用try-with-resources自动关闭连接
             PreparedStatement pstmt = conn.prepareStatement(
                     "UPDATE merchants SET  store_name = ?, address = ?, " +
                             "phone = ?, email = ?, password = ?"+
                             "WHERE merchant_id = ?")) { // 准备SQL语句以更新产品

            // 设置更新的字段值
            pstmt.setString(1, merchants.getStore_name());
            pstmt.setString(2, merchants.getAddress());
            pstmt.setString(3, merchants.getPhone());
            pstmt.setString(4, merchants.getEmail());
            pstmt.setString(5, merchants.getPassword());
            pstmt.setInt(6, merchants.getMerchant_id());

            // 执行更新
            pstmt.executeUpdate();

        } catch (SQLException e) {
            // 处理数据库相关的异常
            e.printStackTrace(); // 这只是暂时的，你应该使用更合适的日志记录方法
            // 在这里你可以抛出异常或进行其他错误处理
        }
    }

}
